/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package webservices;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.NodeList;

/**
 *
 * @author Val
 */
public class Google extends AbstractWebService{
    private static final String URL = "http://maps.googleapis.com/maps/api/";
    private static int rps = 8;

    private static ExecutorService pool = Executors.newFixedThreadPool(4);
    private static final long DELAY = 100;
    private static final long RETRY_BONUS = 50;

    public static String[] getCoords(String nom, String pays) throws ParserConfigurationException, XPathExpressionException {
        NodeList nodes = null;
        long ellapsedTime, sleepTime, currentTime, previousTime = System.currentTimeMillis();
        boolean retry;
        do{
            retry = false;
            nodes = parseNodeList(URL + "geocode/xml?address=" + nom + ",+" + pays + "&sensor=false",
                "//status/text()|//geometry/location/lat/text()|//geometry/location/lng/text()");
            if(nodes.item(0).getNodeValue().equals("OVER_QUERY_LIMIT")) {
                retry = true;
                System.out.println("retry");
            }
            currentTime = System.currentTimeMillis();
            try {
                ellapsedTime = currentTime -  previousTime;
                sleepTime = DELAY + (retry ? RETRY_BONUS : 0);
                Thread.sleep(sleepTime - (ellapsedTime < sleepTime ? ellapsedTime : 0) );
            } catch (InterruptedException ex) {
                Logger.getLogger(Google.class.getName()).log(Level.SEVERE, null, ex);
            }
            previousTime = currentTime;
        } while (retry);
        return new String[] {
            nodes.item(1).getNodeValue(),
            nodes.item(2).getNodeValue()};
    }

}
